package com.kool.kadmin.common.util;

import com.kool.kadmin.common.constant.ErrorCode;
import com.kool.kadmin.common.exception.AppException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author luyu
 */
public class ValidateUtil {
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 校验
     *
     * @param obj
     * @param <T>
     */
    public static <T> void valid(T obj) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        if (constraintViolations.size() > 0) {
            throw new AppException(ErrorCode.BUSINESS_ERROR, String.format("参数校验失败:%s", constraintViolations.iterator().next().getMessage()));
        }
    }
}
